/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * 加解密工具类
 *
 * @auther ebert_chan
 */
public class CryptHelper {

    private static final Logger LOGGER = LoggerFactory.getLogger(CryptHelper.class);

    public static final String DEFAULT_CHARSET = "UTF-8";

    /**
     * url编码字符串
     *
     * @param s
     * @return
     * @auther ebert_chan
     */
    public static String urlEncoder(String s) {
        return urlEncoder(s, DEFAULT_CHARSET);
    }

    /**
     * url编码字符串
     *
     * @param s
     * @param charset
     * @return
     * @auther ebert_chan
     */
    public static String urlEncoder(String s, String charset) {
        String encodeStr = null;
        try {
            encodeStr = URLEncoder.encode(s, charset);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding", e);
        }
        return encodeStr;
    }

    /**
     * url解码字符串
     *
     * @param encodeStr
     * @return
     * @auther ebert_chan
     */
    public static String urlDecoder(String encodeStr) {
        return urlDecoder(encodeStr, DEFAULT_CHARSET);
    }

    /**
     * url解码字符串
     *
     * @param encodeStr
     * @param charset
     * @return
     * @auther ebert_chan
     */
    public static String urlDecoder(String encodeStr, String charset) {
        String decodeStr = null;
        try {
            decodeStr = URLDecoder.decode(encodeStr, charset);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding", e);
        }
        return decodeStr;
    }

    /**
     * 对字符串进行base64编码
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static String base64Encrypt(String text) {
        byte[] data = stringToBytes(text);
        if (data == null) {
            return null;
        }
        return base64EncryptInline(data);
    }

    /**
     * 对二进制数据进行base64编码
     *
     * @param data
     * @return
     * @auther ebert_chan
     */
    public static String base64Encrypt(byte[] data) {
        if (data == null) {
            return null;
        }
        return Base64.getEncoder().encodeToString(data);
    }

    /**
     * 对二进制数据进行base64编码，编码后的密文去除空格保持为一行
     *
     * @param data
     * @return
     * @auther ebert_chan
     */
    public static String base64EncryptInline(byte[] data) {
        String str = base64Encrypt(data);
        if (str != null) {
            return str.replaceAll("\\s", "");
        }
        return str;
    }

    /**
     * 对base64密文进行解密
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static String base64Decrypt(String text) {
        byte[] buffer = base64DecryptToBuffer(text);
        return bytesToString(buffer);
    }

    /**
     * 对base64密文进行解密
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static byte[] base64DecryptToBuffer(String text) {
        if (text == null) {
            return null;
        }
        byte[] buffer = Base64.getDecoder().decode(text);
        return buffer;
    }

    /**
     * 生成md5摘要
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static String md5(String text) {
        byte[] data = stringToBytes(text);
        if (data == null) {
            return null;
        }
        String md5 = md5(data);
        return md5;
    }

    /**
     * 生成md5摘要
     *
     * @param data
     * @return
     * @auther ebert_chan
     */
    public final static String md5(byte[] data) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(data);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            LOGGER.error("An exception occurred.", e);
        }
        return null;
    }

    /**
     * string转byte[]，使用默认字符编码
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static byte[] stringToBytes(String text) {
        if (text == null) {
            return null;
        }
        try {
            byte[] data = text.getBytes(DEFAULT_CHARSET);
            return data;
        } catch (UnsupportedEncodingException e) {
            LOGGER.warn("Unsupported encoding", e);
        }
        return null;
    }

    public static String bytesToString(byte[] buffer) {
        if (buffer == null) {
            return null;
        }
        try {
            return new String(buffer, DEFAULT_CHARSET);
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding", e);
        }
        return null;
    }

    /**
     * sha1
     *
     * @param text
     * @return
     * @auther ebert_chan
     */
    public static String sha1(String text) {
        return sha1(text, DEFAULT_CHARSET);
    }

    /**
     * sha1
     *
     * @param text
     * @param charset
     * @return
     * @auther ebert_chan
     */
    public static String sha1(String text, String charset) {
        MessageDigest sha = null;
        try {
            sha = MessageDigest.getInstance("SHA");

            byte[] byteArray = text.getBytes(charset);
            byte[] cipherBytes = sha.digest(byteArray);

            String hexValue = byteToHex(cipherBytes);
            return hexValue;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error("Unsupported encoding", e);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("An exception occurred.", e);
        }
        return null;
    }

    /**
     * 数组转为十六进制字符串
     * <p>
     *
     * @param bytes
     * @return java.lang.String
     * @author ebert_chan
     * @date 2024/6/5
     */
    public static String byteToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            // 将有符号字节转为无符号整数
            int num = bytes[i] & 0xFF;
            // 将整数转为十六进制字符串
            String hex = Integer.toHexString(num);
            if (hex.length() == 1) {
                // 在单个字符的十六进制数前补充一个0
                sb.append('0');
            }
            sb.append(hex);
        }
        return sb.toString();
    }

    /**
     * 十六进制字符串转为数组
     * <p>
     *
     * @param hexString
     * @return byte[]
     * @author ebert_chan
     * @date 2024/6/5
     */
    public static byte[] hexToByte(String hexString) {
        int len = hexString.length();
        byte[] byteArray = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4) + Character.digit(hexString.charAt(i + 1), 16));
        }
        return byteArray;
    }

}
